package com.li.configserve.controller;

import com.alibaba.fastjson.JSON;
import com.li.configserve.domain.common.CurrentUser;
import com.li.configserve.domain.common.PageParam;
import com.li.toolkit.constant.LogConst;
import com.li.toolkit.constant.NumConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @description: 基础的类
 * @author: Lidong
 * @time: 2020/7/29 21:14
 **/
public class BaseController {

    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    @Autowired
    protected HttpServletRequest request;

    /**
     * @return java.util.Map<java.lang.String, java.lang.String>
     * @Author LiDong
     * @Description //TODO 处理HttpServletRequest拿到参数的Map
     * @Date 20:17 2020/11/30
     * @Param [request]
     **/
    public Map<String, String> getParamMap(HttpServletRequest request) {
        try {
            if (Objects.isNull(this.request)) {
                this.request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
            }
            Map<String, String[]> parameterMap = this.request.getParameterMap();
            Map<String, String> map = new HashMap<>(NumConst.MAP_SIZE);
            // 以form的方式传递参数
            if (parameterMap != null && parameterMap.size() > 0) {
                for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                    String value = entry.getValue()[0];
                    map.put(entry.getKey(), String.valueOf(value));
                }
                return map;
            } else {
                // 从流中读取参数
                ServletInputStream inputStream = request.getInputStream();
                StringBuilder stringBuilder = new StringBuilder();
                int data;
                while ((data = inputStream.read()) != -1) {
                    stringBuilder.append((char) data);
                }
                String res = String.valueOf(stringBuilder);
                try {
                    Map paramMap = JSON.parseObject(res, Map.class);
                    Map<String, String> tempMap = new HashMap<>(NumConst.MAP_SIZE);
                    paramMap.forEach((k, v) -> tempMap.put(String.valueOf(k), String.valueOf(v)));
                    return tempMap;
                } catch (Exception e) {
                    logger.error("error occur :", e);
                }
                return new HashMap<>(1);
            }
        } catch (Exception e) {
            logger.error("=====>getParamMap()出错", e.getMessage(), e);
            return new HashMap<>(1);
        }
    }

    /**
     * 获取分页参数
     *
     * @param request
     * @return
     */
    public PageParam getPageParam(HttpServletRequest request) {
        PageParam pageParam = new PageParam();
        Map<String, String> paramMap = getParamMap(request);
        if (Objects.nonNull(paramMap)) {
            // 分页参数初始化
            String pageNumber = paramMap.get("pageNumber");
            String pageSize = paramMap.get("pageSize");
            if (Objects.nonNull(pageNumber) && Objects.nonNull(pageSize)) {
                pageParam.setPageNumber(Integer.valueOf(pageNumber));
                pageParam.setPageSize(Integer.valueOf(pageSize));
            }
            paramMap.remove("pageNumber");
            paramMap.remove("pageSize");
        }
        pageParam.setParmaMap(paramMap);
        return pageParam;
    }


    /**
     * @return com.li.core.domain.common.CurrentUser
     * @Author LiDong
     * @Description //TODO 得到当前Session中的信息
     * @Date 20:07 2020/11/30
     * @Param []
     **/
    public CurrentUser getCurrentUser() {
        try {
            if (Objects.isNull(request)) {
                request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
            }
            Object user = request.getSession().getAttribute("user");
            if (user == null) {
                return null;
            }
            return (CurrentUser) user;
        } catch (Exception e) {
            logger.error("=====>getCurrentUser()出错:", e.getMessage(), e);
            return null;
        }

    }

    /**
     * 封装Post查询Es中的结果
     */
    public String getEsResultBysql(String sql) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuffer result = new StringBuffer();
        try {
            // 请求的Url
            String urlLocation = "http://127.0.0.1:9200/_sql";
            // 请求体
            String content = "{\"query\":\"" + sql + "\"}";
            URL realUrl = new URL(urlLocation);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            ((HttpURLConnection) conn).setRequestMethod("POST");
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(content);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            logger.info("发送 POST 请求出现异常！" + e);
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                logger.error(LogConst.LOG_FAILURE_PREFIX + ex.getMessage());
            }
        }
        return String.valueOf(result);
    }

}
